package com.shanghaionstar.discover.dealer.presenter;

import android.os.Handler;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.dealer.Pageables;
import com.onstar.cn.mag.dealer.PreferredDealerEntity;
import com.onstar.cn.more.response.LookupAroundDealerResponse;
import com.shanghaionstar.activity.DiscoverActivity;
import com.shanghaionstar.discover.dealer.iview.IChangePreferDealerView;
import com.shanghaionstar.discover.dealer.service.PreferDealerService;
import com.shanghaionstar.discover.model.ProvinceCityConstants;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.LoadCityCode;
import com.shanghaionstar.utils.LoadCityList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import rx.functions.Action1;

/**
 * Created by 7828wc on 16/7/19.
 */
public class ChangePreferDealerPresenter extends BasePresenter<Object> {
    private IChangePreferDealerView mPreferDealerView;
    private BaseActivity mContext;
    private PreferDealerService mService;
    private List<PreferredDealerEntity> aroundDealer = new ArrayList<PreferredDealerEntity>();
    private double latitude = 0;
    private double longitude = 0;
    private String cityCode = "";
    private int pageNumber = 0;
    private int pageSize = 10;// 分页


    private List<String> provinces;
    private List<String> cityList = new ArrayList<String>();
    private ProvinceCityConstants provinceCityConstants;


    public ChangePreferDealerPresenter(IMVPScheduler mvpScheduler) {
        super(mvpScheduler);
    }

    @Override
    public void setView(IMVPView<Object> view) {
        super.setView(view);
        mPreferDealerView = (IChangePreferDealerView) view;
        mContext = (BaseActivity) mPreferDealerView.onActivity();
        mService = new PreferDealerService(mContext);
    }

    public void loadDatas() {
        mPreferDealerView.setLoading(true);
        subscription = mService.loadDatas(cityCode,latitude,longitude,pageNumber,pageSize).subscribeOn(mvpScheduler.backgroundThread()).observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<LookupAroundDealerResponse>() {
                    @Override
                    public void call(LookupAroundDealerResponse aroundDealerResponse) {
                        mPreferDealerView.setLoading(false);
                        try {
                            cityCode = aroundDealerResponse.getDealers().get(pageNumber)
                                    .getCityCode();
                            if (pageNumber < 1) {
                                if (aroundDealer != null) {
                                    aroundDealer.clear();
                                }
                                aroundDealer = aroundDealerResponse.getDealers();
                                String cityName = new LoadCityCode(mContext).findZhCityByCityCode(cityCode);
                                mPreferDealerView.onPageInit(aroundDealer, cityName);
                            } else {
                                List<PreferredDealerEntity> list = aroundDealerResponse.getDealers();
                                if (list != null && list.size() > 0) {
                                    list.remove(0);
                                    aroundDealer.addAll(list);
                                }
                                mPreferDealerView.notifyDataChange();
                            }
                            Pageables pageables = aroundDealerResponse.getPageable();
                            int pageSize = pageables.getPageSize();
                            int totalSize = pageables.getTotalSize();
                            mPreferDealerView.showMore(pageSize<totalSize);
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        mPreferDealerView.setLoading(false);
                        if(throwable != null && mPreferDealerView != null)
                            mPreferDealerView.onResponseError((OnStarException) throwable);
                    }
                });
    }


    public void getCoordinate() {
        String latitudes = PreferencesUtls.getInstance(mContext).getString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_LOCATION_LATITUDE);
        String longitudes = PreferencesUtls.getInstance(mContext).getString(FinalConstants.SharedPreferencesConfig.USER_CURRENT_LOCATION_LONGITUDE);
        if (!CommonUtil.isNull(latitudes) && !CommonUtil.isNull(longitudes)) {
            latitude = Double.parseDouble(latitudes);
            longitude = Double.parseDouble(longitudes);
        }
    }

    public void onDealerItemClick(int position) {
        if (aroundDealer != null && aroundDealer.size() > 0) {
            if (mContext instanceof DiscoverActivity) {
                ((DiscoverActivity) mContext).setPreEntity(aroundDealer.get(position));
            }
        }
    }

    public void getProvince(){
        provinceCityConstants = new ProvinceCityConstants();
        provinces  = new ArrayList<String>();
//        for(String province : ProvinceCityConstants.PROVINCE){
//            provinces.add(province);
//        }
        Collections.addAll(provinces,ProvinceCityConstants.PROVINCE);
        mPreferDealerView.setupProvinceAdapter(provinces);
    }

    private int curProvincePos =-1;

    public void onLeftItemClick(int position){
        curProvincePos = position;
        cityList.clear();
        String[] citys = ProvinceCityConstants.CITY[position];
//        for(String city : citys){
//            cityList.add(city);
//        }
        Collections.addAll(cityList,citys);
        mPreferDealerView.setupCityAdapter(cityList);
    }

    public void onRightItemClick(int position){
//        final ProvinceCityConstants provinceCityConstants = new ProvinceCityConstants();
        if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
            LoadCityList loadFile = new LoadCityList(mContext);
            cityCode = new LoadCityCode(mContext)
                    .findCityCodeByZhCity(loadFile.findByZhCity(ProvinceCityConstants.CITY[curProvincePos][position]));
        } else {
            cityCode = new LoadCityCode(mContext)
                    .findCityCodeByZhCity(ProvinceCityConstants.CITY[curProvincePos][position]);
        }
        pageNumber = 0;
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                loadDatas();
                mPreferDealerView.onRightItemClick();
            }
        }, 500);
    }

    public void moreClick() {
        pageNumber += 1;
        pageSize += pageSize;
        loadDatas();
    }
}
